package com.vieewer.btdemo.view.net.connect;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.vieewer.btdemo.app.App;
import com.vieewer.btdemo.bean.*;
import com.vieewer.btdemo.utils.*;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

public class ConnectWifTools {

    private static final String TAG = "ConnectWifiActivity";

    //private ListView listView;
    //private TextView tv;
    //private EditText edt_input_pwd;
    //private ListAdapter adapter;
    private List<ScanResult> mWifiList = new ArrayList<>(); //wifi列表
    private WifiBroadcastReceiver wifiReceiver;
    private WifiUtils mUtils;
    private Context mContext;

    private static final int WIFICIPHER_NOPASS = 1;
    private static final int WIFICIPHER_WEP = 2;
    private static final int WIFICIPHER_WPA = 3;

    private boolean hasSendSuccess = false;
    private boolean hasSendFailed = false;
    private boolean hasSendPwdError = false;

    private boolean bConnectedWifiNotFinished = false;

    private String mCurWifiName = "";
    private onNetWorkStateChangeListener mListener;
    private WifiManager wifiManager;


    private ConnectWifTools() {

    }



    private static class Instance {
        public static ConnectWifTools singletonState = new ConnectWifTools();
    }

    public static ConnectWifTools getNewInstance() {
        return Instance.singletonState;
    }


    public void init(Context context) {
        mContext = context;
        mUtils = new WifiUtils(context);
        wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    }




    private void registerBroadCast() {
        //注册广播
        wifiReceiver = new WifiBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);//监听wifi是开关变化的状态
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);//监听wifiwifi连接状态广播
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);//监听wifi列表变化（开启一个热点或者关闭一个热点）
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); //监听wifi连接密码是否错误
        mContext.registerReceiver(wifiReceiver, filter);
    }


    private void unRegisterBroadCast() {
        //取消监听
        mContext.unregisterReceiver(wifiReceiver);
    }





    /**
     * 扫描附近wifi
     */
    private void scanWifiInfo() {

        wifiManager.setWifiEnabled(true);
        wifiManager.startScan();

        mWifiList.clear();
        mWifiList = wifiManager.getScanResults();

        //todo 收到手机端搜索信号 把搜索结果发送给手机端
        sendScanWifiResultToPhone();
    }

    private void sendScanWifiResultToPhone() {

        List<MyScanResult> datas = new ArrayList<>();
        for (int i = 0 ; i < mWifiList.size(); i++) {
            MyScanResult bean = new MyScanResult();
            bean.capabilities = mWifiList.get(i).capabilities;
            bean.level = mWifiList.get(i).level;
            bean.ssid = mWifiList.get(i).SSID;
            datas.add(bean);
        }
        WifiResultBean data = new WifiResultBean();
        data.wifiResultDatas = datas;
        data.type = "wifiResult";
        String dataStr = JSON.toJSONString(data);
        LogUtil.e("yjj", "send scan wifi result to phone>>>"  + dataStr);

        CommunicateToPhoneHelper.Companion.getInstance().write(dataStr);

    }

    public boolean getSwitchWifiStatus() {
        //获取wifi开关状态
        int status = wifiManager.getWifiState();
        if (status == WifiManager.WIFI_STATE_ENABLED) {
            return true;
        } else {
            return false;
        }
    }



    public void changeWifiStatus(boolean changeNetStatus) {
        //获取wifi开关状态
        int status = wifiManager.getWifiState();

        if (changeNetStatus) {  //打开wifi

            if (status == WifiManager.WIFI_STATE_DISABLED) {
                //关闭状态则打开
                wifiManager.setWifiEnabled(true);
                Toast.makeText(mContext, "wifi已打开", Toast.LENGTH_SHORT).show();

                if (mListener != null) {
                    mListener.onNetWorkStateChange(true);
                }
            }

        } else {   //关闭wifi

            if (status == WifiManager.WIFI_STATE_ENABLED ) {
                //wifi打开状态则关闭
                wifiManager.setWifiEnabled(false);
                Toast.makeText(mContext, "wifi已关闭", Toast.LENGTH_SHORT).show();

                if (mListener != null) {
                    mListener.onNetWorkStateChange(false);
                }
            }
        }

    }



    public void connect(WifiLinkBean bean) {

        if (mWifiList != null && mWifiList.size() > 0) {

            WifiLinkBean.ScanResultBean scanResult = bean.getScanResult();

            // 判断密码输入情况
            if (TextUtils.isEmpty(bean.getPsd())) {
                Toast.makeText(mContext, "请输入wifi密码", Toast.LENGTH_SHORT).show();
                return;
            }

            hasSendSuccess = false;
            hasSendFailed = false;
            hasSendPwdError = false;
            bConnectedWifiNotFinished = false;
            mCurWifiName = scanResult.getSsid();


            registerBroadCast();
            //todo 连接wifi
            Log.i(TAG, "connect wifi >>>" + bean.getPsd() + "wifi name ~~~ " + scanResult.getSsid());
            connectWifi(scanResult.getSsid(), bean.getPsd(), mUtils.getWifiEncType(scanResult.getCapabilities()));
        }
    }

    /**
     * 连接wifi
     *
     * @param targetSsid wifi的SSID
     * @param targetPsd  密码
     * @param enc        加密类型
     */
    @SuppressLint("WifiManagerLeak")
    public void connectWifi(String targetSsid, String targetPsd, int enc) {
        // 1、注意热点和密码均包含引号，此处需要需要转义引号
        String ssid = "\"" + targetSsid + "\"";
        String psd = "\"" + targetPsd + "\"";

        //2、配置wifi信息
/*        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = ssid;
        switch (enc) {
            case "WEP":
                // 加密类型为WEP
                conf.wepKeys[0] = psd;
                conf.wepTxKeyIndex = 0;
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;
            case "WPA":
                // 加密类型为WPA
                conf.preSharedKey = psd;
                break;
            case "OPEN":
                //开放网络
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }*/
        //3、链接wifi

        wifiManager.addNetwork(mUtils.CreateWifiInfo(targetSsid, targetPsd, enc));
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        if (list != null && list.size() > 0) {
            for (WifiConfiguration i : list) {
                if (i.SSID != null && i.SSID.equals(ssid)) {
                    wifiManager.disconnect();
                    wifiManager.enableNetwork(i.networkId, true);
                    wifiManager.reconnect();
                    break;
                }
            }
        }

    }

    //监听wifi状态广播接收器
    public class WifiBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {

                int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (state) {
                    /**
                     * WIFI_STATE_DISABLED    WLAN已经关闭
                     * WIFI_STATE_DISABLING   WLAN正在关闭
                     * WIFI_STATE_ENABLED     WLAN已经打开
                     * WIFI_STATE_ENABLING    WLAN正在打开
                     * WIFI_STATE_UNKNOWN     未知
                     */
                    case WifiManager.WIFI_STATE_DISABLED: {
                        Log.i(TAG, "已经关闭");
                        break;
                    }
                    case WifiManager.WIFI_STATE_DISABLING: {
                        Log.i(TAG, "正在关闭");
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLED: {
                        Log.i(TAG, "已经打开");
//                        sortScaResult();
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLING: {
                        Log.i(TAG, "正在打开");
                        break;
                    }
                    case WifiManager.WIFI_STATE_UNKNOWN: {
                        Log.i(TAG, "未知状态");
                        break;
                    }
                }
            } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                Log.i(TAG, "--NetworkInfo--" + info.toString());
                bConnectedWifiNotFinished = false;

                if (NetworkInfo.State.DISCONNECTED == info.getState()) {//wifi没连接上
                    if (!hasSendFailed) {
                        Log.i(TAG, "wifi没连接上111");
                        hasSendFailed = true;
                        //判断wifi连接是否finish
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (!bConnectedWifiNotFinished) { //防止wifi连接成功的情况下还会回调这个方法

                                    sendFailedMsgToPhone();
                                    if (mListener != null) {
                                        mListener.onNetWorkStateChange(false);
                                    }
                                    Log.i(TAG, "wifi没连接上222");

                                }
                            }
                        }, 2*1000);


                    }
                } else if (NetworkInfo.State.CONNECTED == info.getState()) {//wifi连接上了
                    Log.i("yjj", "name 111" + SugonInfoUtils.Companion.getConnectWifiSsid(mContext));
                    Log.i("yjj", "name 222" + mCurWifiName);
                    if (!hasSendSuccess) {
                        sendSuccessToPhone();
                        Log.i(TAG, "wifi连接上了");
                        if (mListener != null) {
                            mListener.onNetWorkStateChange(true);
                        }
                        hasSendSuccess = true;
                        bConnectedWifiNotFinished = false; //wifi连接结束
                        unRegisterBroadCast();
                    }
                } else if (NetworkInfo.State.CONNECTING == info.getState()) {//正在连接
                    bConnectedWifiNotFinished = true;
                    Log.i(TAG, "wifi正在连接");
                }




            } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
                Log.i(TAG, "网络列表变化了");
            } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {

       /*         if (!hasSendPwdError) {
                    Log.e(TAG, "wifi密码错误广播");
                    //ToastUtil.shortToast("密码错误");
                    sendPwdErrorMsgToPhone();
                    hasSendPwdError = true;
                }*/

                //int linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 123);
                //if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {

                //}

            }
        }
    }


    private void sendSuccessToPhone() {

            SugonInfoBean data = new SugonInfoBean();
            data.type = "wifi_connect_success";
            data.bluetoothName = SugonInfoUtils.Companion.getBluetoothName();
            data.connectWifiName = SugonInfoUtils.Companion.getConnectWifiSsid(mContext);
            data.diskValue = SugonInfoUtils.Companion.getDiskValue();
            data.totalValue = SugonInfoUtils.Companion.getDiskTotal();
            String dataStr = JSON.toJSONString(data);
            LogUtil.e("yjj", "sendSuccessToPhone");
            CommunicateToPhoneHelper.Companion.getInstance().write(dataStr);

    }

    private void sendFailedMsgToPhone() {

        WifiConnectFailedBean data = new WifiConnectFailedBean();
        data.type = "wifi_connect_failed";
        LogUtil.e("yjj", "connect wifi failed , send to phone");
        String dataStr = JSON.toJSONString(data);
        CommunicateToPhoneHelper.Companion.getInstance().write(dataStr);

    }


    private void sendPwdErrorMsgToPhone() {

        WifiConnectFailedBean data = new WifiConnectFailedBean();
        data.type = "wifi_connect_pwd_wrong";
        data.ret = "密码错误，请重新连接wifi~";
        LogUtil.e("yjj", "connect wifi failed >>>> pwd error , send to phone");
        String dataStr = JSON.toJSONString(data);
        CommunicateToPhoneHelper.Companion.getInstance().write(dataStr);

    }


    public void scanWifi() {
        hasSendSuccess = false;
        hasSendFailed = false;
        //要定位权限才能搜索wifi
        WifiPermissionUtil.requestEach((Activity) mContext, new WifiPermissionUtil.OnPermissionListener() {
            @Override
            public void onSucceed() {
                //授权成功后打开wifi
                scanWifiInfo();
            }

            @Override
            public void onFailed(boolean showAgain) {

            }
        }, WifiPermissionUtil.LOCATION);

    }


    public interface onNetWorkStateChangeListener {
        public void onNetWorkStateChange(boolean isConnected);
    }

    public void setOnNetWorkStateChangeListener(onNetWorkStateChangeListener listener) {
        mListener = listener;
    }


}
